package com.liang.blog.auth.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.util.AntiCollisionHashMap;
import com.liang.blog.auth.service.AuthService;
import com.liang.blog.client.user.UserFeignClient;
import com.liang.blog.common.exception.BlogException;
import com.liang.blog.common.result.Result;
import com.liang.blog.model.BlogUser;
import com.liang.blog.model.constant.CacheConstants;
import com.liang.blog.redis.service.RedisService;
import com.liang.blog.security.jwt.AuthContextHolder;
import com.liang.blog.security.jwt.JwtHelper;
import com.liang.blog.security.utils.BlogSecurityUtil;
import com.liang.blog.vo.user.LoginUserVo;
import com.liang.blog.vo.user.LoginVo;
import com.liang.blog.vo.user.RegisterVo;
import org.apache.shiro.SecurityUtils;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @Author：YanWenLiang
 * @Date:2023-08-17-17:28
 */
@RestController
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserFeignClient userFeignClient;

    /**
     * 登入
     * @param loginVo
     * @return
     */
    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo, HttpServletRequest request) throws UnknownHostException {
        Map<String, String> loginInfo = authService.login(loginVo);
        InetAddress address = InetAddress.getLocalHost();
        String ipv4Address = address.getHostAddress();
        userFeignClient.setLoginIp(ipv4Address, loginVo.getAccount());
        return Result.ok(loginInfo);
    }

    /**
     * 邮箱登入
     * @param loginVo
     * @return
     * @throws UnknownHostException
     */
    @PostMapping("emailLogin")
    public Result emailLogin(@RequestBody LoginVo loginVo) throws UnknownHostException {
        Map<String, String> map = authService.emailLogin(loginVo);
        InetAddress address = InetAddress.getLocalHost();
        String ipv4Address = address.getHostAddress();
        userFeignClient.setLoginIp(ipv4Address, map.get("account"));
        return Result.ok(map);
    }

    /**
     * 退出
     * @return
     */
    @RequestMapping("logout")
    public Result logoutHandler(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        String token = AuthContextHolder.getToken(request);
        String userKey = JwtHelper.getUserKey(token);
        redisService.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + userKey);
        BlogSecurityUtil.remove();
        return Result.ok();
    }

    /**
     * 根据 token 获取用户信息
     * @param token
     * @return
     */
    @GetMapping("userInfo")
    public Result getUserInfoByToken(@RequestParam("token") String token){
        LoginUserVo loginUserVo = authService.getUserInfoVoByToken(token);
        return Result.ok(loginUserVo);
    }

    /**
     * 注册
     * @param registerVo
     * @return
     */
    @PostMapping("register")
    public Result register(@RequestBody RegisterVo registerVo){
        return Result.ok(authService.register(registerVo));
    }

    @GetMapping("sendRegisterEmail/{email}/{uuid}")
    public Result sendRegisterEmail(@PathVariable String email, @PathVariable String uuid){
        return Result.ok(authService.registerEmail(email, uuid));
    }

    @GetMapping("sendLoginEmail/{email}/{uuid}")
    public Result sendLoginEmail(@PathVariable String email, @PathVariable String uuid){
        return Result.ok(authService.loginEmail(email, uuid));
    }

//    @GetMapping("sendRegisterEmail/{email}/{uuid}")
//    public Result sendRegisterEmail(@PathVariable String email, @PathVariable String uuid) {
//        CompletableFuture<Boolean> booleanCompletableFuture = authService.registerEmail(email, uuid);
//        booleanCompletableFuture.thenAccept(
//                result -> {
//                    if (result) {
//                        System.out.println("邮件发送成功");
//                    } else {
//                        System.out.println("邮件发送失败");
//                    }
//                }
//        );
//        return Result.ok(true);
//    }

    /**
     * 获取验证码
     * @param uuid
     * @param request
     * @param response
     */
    @GetMapping("/verifyCode/{uuid}")
    public void getVerifyCode(@PathVariable String uuid, HttpServletRequest request, HttpServletResponse response) {
        authService.getVerifyCode(uuid, response);
    }




}
